package model.dao;

import java.io.Serializable;
import java.util.ArrayList;
import model.dao.ulti.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public abstract class AbstractDAO<P, K extends Serializable>{
    protected abstract Class getPOJOClass();
    public P get(K key) throws HibernateException{
       Session session = HibernateUtil.getSessionFactory().openSession();
       P p = (P)session.get(this.getPOJOClass(), key);
       session.close();
       return p;
    }
    public ArrayList<P> getList()throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql  = String.format("select obj from %s obj", this.getPOJOClass().getName());
        Query query = session.createQuery(hql);
        ArrayList<P> list = (ArrayList<P>) query.list();
        session.close();
        return list;
    }
    public void saveOrUpdate(P p)throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction trans = session.beginTransaction();
        try{
            session.saveOrUpdate(p);
            trans.commit();
        }catch(HibernateException ex){
            trans.rollback();
            throw ex;
        }finally{
            session.close();
        }    
    }
    public void  delete(P p) throws HibernateException{
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction trans = session.beginTransaction();
        try{
            session.delete(p);
            trans.commit();
        }catch(HibernateException ex){
            trans.rollback();
            throw ex;
        }finally{
            session.close();
        }            
    }
}
